<template>
  <section>
    <!--search-->
    <el-col :span="24" style="padding-top: 10px;margin-left: 10px">
      <el-form :inline="true" :model="filters" size="small">
        <el-form-item>
          <el-input  style="width: 200px" v-model="filters.tag" placeholder="search by Tag,split by ','" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-tooltip effect="dark" content="when no content,click will refresh table" placement="bottom-start">
            <el-button type="primary"  v-on:click="getTestCase()">Search</el-button>
          </el-tooltip>
          <el-button type="primary"  v-on:click="handleAdd()" icon="el-icon-plus">Test Case</el-button>
          <el-button type="warning"  v-on:click="prepareTestCaseData()" :disabled="prepareDataBtn">Prepare Data</el-button>
          <el-button type="warning"  v-on:click="runTestCase()" :disabled="runTestCaseBtnDisabled">Run Test Case</el-button>
          <el-button type="primary"  v-on:click="exportDB()">Export DB to PCM</el-button>
          <el-button type="primary"  v-on:click="importDB()">Import DB from PCM</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!-- table -->
    <el-table :data="testCaseData"  highlight-current-row v-loading="listLoading" @selection-change="selsChange" size="small"  :border="true" empty-text="empty">
      <el-table-column type="selection" width="55" header-align="center">
      </el-table-column>
      <!--<el-table-column type="expand" label="Ref">-->
        <!--<testCaseCard slot-scope="props" :props="props"></testCaseCard>-->
      <!--</el-table-column>-->
      <el-table-column prop="testCaseName" label="Test Case Name" width="200" sortable header-align="center">
      </el-table-column>
      <!--<el-table-column prop="testCaseId" label="Test Case Id" width="200" sortable header-align="center">-->
      <!--</el-table-column>-->
      <el-table-column label="Relationship" width="600" align="left" header-align="center" >
        <template slot-scope="scope" >
          <div :ref="scope.row.relationship._id" ></div>
        <!--<div >-->
          <!--<ul id="demo">-->
            <!--<relationDependency-->
              <!--class="item"-->
              <!--:model="scope.row.urls"-->
            <!--&gt;-->
            <!--</relationDependency>-->
          <!--</ul>-->
        <!--</div>-->
          <!--<el-form size="mini">-->
            <!--<el-form-item :label="'Url'+(index+1)+':'" v-for="(url,index) in scope.row.urls">-->
              <!--<div ><span>{{url.url}}</span></div>-->
            <!--</el-form-item>-->
          <!--</el-form>-->
        </template>
      </el-table-column>
      <el-table-column prop="bizKey" label="BizKey" sortable header-align="center">
        <template slot-scope="props">
          <div v-for="(bizKey,index) in props.row.bizKey">
          <span>{{bizKey.bizKeyType}} : </span>
          <span>{{bizKey.bizKeyValue}} </span>
        </div>
        </template>
      </el-table-column>
      <el-table-column prop="inQueue" label="InQueue"  sortable header-align="center">
      </el-table-column>
      <el-table-column  label="Verifier" width="150" sortable header-align="center">
        <template slot-scope="scope">
            <el-tag size="mini" v-for="(verifier,index) in scope.row.verifiers">
              {{verifier}}
            </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Tag" width="100" sortable header-align="center">
        <template slot-scope="scope">
            <el-tag size="mini" type="success" v-for="(tag,index) in scope.row.tags">
              {{tag}}
            </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Operation"header-align="center" width="200">
        <template slot-scope="scope">
          <el-button size="small" type="text" icon="el-icon-document" v-on:click="handleCopy(scope.$index,scope.row)">Copy</el-button>
          <el-button size="small" type="text" icon="el-icon-edit" v-on:click="handleEdit(scope.$index,scope.row)">Edit</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" v-on:click="handleDel(scope.$index, scope.row)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--bulk delete -->
    <el-col :span="24" align="left">
      <el-button type="danger" v-on:click="batchRemove" size="small" :disabled="this.sels.length===0">Delete Selected</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>
  </section>
</template>


<script>
  import testCaseCard from './TestCaseCard.vue'
  import relationDependency from './RelationDependency.vue'
  import * as leaderLine from 'leader-line';
  /* eslint-disable */
  export default{
    data(){
      return {
        lightWeightTestCaseList:[],
        startElement:{},
        prepareDataBtn:true,
        runTestCaseBtnDisabled:true,
        lineArr:[],
        currentSelection:{},
        relationships:[],
        urls:[],
        open:false,
        page: 1,
        total:0,
        pageSize:5,
        filters: {
          tag: ''
        },
        testCaseData:[],
        listLoading: false,
        sels: [],
        orderedDependenciesList: [],
        editTestCaseForm:{},
      }
    },
    watch: {
    },
    components: {
      testCaseCard,
      relationDependency
    },
    computed: {

    },

    methods:{
      handleCurrentChange: function (val) {
        this.page = val;
        this.testCaseData=[];
        this.removeLeaderLine();
        this.getTestCase();
      },
      getTestCaseHttp: function (url) {
        this.testCaseData=[];
        this.removeLeaderLine();
        this.listLoading = true;
        this.$http.get(url).then((res)=>{
          if(res.body.status==='400'){
            this.$message({
              message:res.body.reason,
              type:'error'
            })
          }  else {
            this.testCaseData = res.body.data;
            this.total = res.body.total;
            this.listLoading = false;
            this.buildRelationship();
          }
        });
      },
      buildRelationship : function () {
        this.testCaseData.forEach((item,index) => {
          if(JSON.stringify(item.relationship) !== JSON.stringify({})) {
            if(item.relationship.dependency.length === 0){
              return;
            } else {
            this.$nextTick(() => {
              this.startElement = document.createElement("div");
              this.startElement.setAttribute("id", item.relationship._id + '_' + item.relationship.testCaseId);
              this.startElement.setAttribute("class", "root");
              let secondCircle = document.createElement("div");
              secondCircle.setAttribute("class", "secondCircle");
              this.startElement.append(secondCircle);
              this.$refs[item.relationship._id].appendChild(this.startElement);
              if (item.relationship.dependency && item.relationship.dependency.length) {
                this.parseRelationship(item.relationship._id, item.relationship.testCaseId, item.relationship.dependency, 1);
                this.startElement.style['position'] = 'absolute';
                this.startElement.style['top'] = '35%';
                if (item.isReady) {
                  for (let node of document.getElementsByClassName(item.relationship._id)) {
                    node.style['border'] = "4px solid rgb(0, 255, 52)";
                  }
                }
              }
            });
            }
          }
        });
      },
      getLightWeightTestCaseList: function () {
        let url = '/testcase/getLightWeightTestCaseList';
        this.$http.get(url).then(res=>{
          if(res.body !== 'ERROR'){
            this.lightWeightTestCaseList = res.body;
          }
        });
      },
      getTestCaseNameByTestCaseId : function (testCaseId) {
        for(let lightWeightTestCase of this.lightWeightTestCaseList){
          if(testCaseId === lightWeightTestCase.testCaseId) {
            return lightWeightTestCase.testCaseName;
          }
        }
      },
      parseRelationship : function (relationshipId, testCaseId, treeNodes, marginLeft) {
        if (!treeNodes || !treeNodes.length) return;
        for (let treeNode of treeNodes) {
          let childs = treeNode.dependency;
          let nextElement = document.createElement("div");
          nextElement.setAttribute("id",relationshipId+'_'+treeNode.testCaseId);
          nextElement.setAttribute("class",relationshipId);
          nextElement.style['border-radius'] = '5px';
          nextElement.style['margin-top'] = '3em';
          nextElement.style['text-align'] = 'center';
          nextElement.style['width'] = '105px';
          nextElement.style['margin-left'] = '20%';
          nextElement.style['overflow'] = 'hidden';
          nextElement.style['display'] = '-webkit-box';
          nextElement.style['-webkit-line-clamp'] = '3';
          nextElement.style['-webkit-box-orient'] = 'vertical';
          nextElement.style['background-color'] = '#409EFF';
//          nextElement.style['left']=marginLeft*20+'px';
          nextElement.text=treeNode.testCaseId;
          let testCaseName = this.getTestCaseNameByTestCaseId(treeNode.testCaseId);
          nextElement.appendChild(document.createTextNode(testCaseName));
          this.$refs[relationshipId].prepend(nextElement);
          this.$nextTick(()=> {
            let line = new LeaderLine(nextElement ,document.getElementById(relationshipId+'_'+testCaseId), {path: 'straight', size: 2});
            this.lineArr.push(line);
//            let line = new LeaderLine(LeaderLine.mouseHoverAnchor(nextElement, 'draw'), document.getElementById(testcaseID), {path: 'straight', size: 2});
          });
          if(childs && childs.length > 0){
            this.parseRelationship(relationshipId,treeNode.testCaseId,childs, (marginLeft+1) );
          }

        }
      },
      getTestCase : function () {
        if(this.filters.tag){
          let url = 'testcase/FilterTestCaseList/'+this.filters.tag+'/'+this.page+'/'+this.pageSize;
          this.getTestCaseHttp(url);
        } else {
          let url = 'testcase/TestCaseList/'+this.page+'/'+this.pageSize;
          this.getTestCaseHttp(url);
        }
      },
      exportDB : function(){
        this.getStatusForExportDBJob();
      },
      importDB : function () {
        this.getStatusForImportDBJob();
      },

      triggerJobBuild : function (url) {
        this.$http.post(url,{}).then((res)=>  {
        })
      },

      getStatusForImportDBJob : function () {
        let url = 'ciGetImportJobStatus';
        this.$http.get(url).then((res)=>  {
          if (res.data.result){
            this.triggerJobBuild('ciTriggerImportJob');
            setTimeout(this._constructTimeoutCallback(res.data.id,1,'PCM_Auto_initial_DB_withData'),2000);
          }else {
            alert("The Job is Runing");
            let url = "http://admin:Password1@cx-pp02-w10:8080/view/PCM_AUTOMATION/job/PCM_Auto_initial_DB_withData/" + res.data.id + "/console";
            window.open(url,'_blank');
          }
        })
      },

      getStatusForExportDBJob : function () {
        let url = 'ciGetExportJobStatus';
        this.$http.get(url).then((res)=>  {
          if (res.data.result){
            this.triggerJobBuild('ciTriggerExportJob');
            setTimeout(this._constructTimeoutCallback(res.data.id,1,'PCM_Auto_Export_Initialized_DB'),2000);
          }else {
            alert("The Job is Runing");
            let url = "http://admin:Password1@cx-pp02-w10:8080/view/PCM_AUTOMATION/job/PCM_Auto_Export_Initialized_DB/" + res.data.id + "/console";
            window.open(url,'_blank');
          }
        })
      },

      _constructTimeoutCallback : function (num, increment,jobName)
      {
        return function()
        {
          let buildNum = parseInt(num) + increment;
          let url = "http://admin:Password1@cx-pp02-w10:8080/view/PCM_AUTOMATION/job/"+jobName + "/"+ buildNum + "/console";
          window.open(url,'_blank');
        }
      },

//      Delete testcase
      handleDel:function(index, row){
        this.$confirm('are you sure?', 'warning', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          let url = 'testcase/remove/'+this.testCaseData[index].testCaseId;
          this.$http.delete(url).then(function(res){
            if(res.body.status==='200'){
              this.listLoading = false;
              this.$message({
                message: 'delete success',
                type: 'success'
              });
              this.getTestCase();
            }
          })
        }).catch((e) => {
          this.$message({message: JSON.stringify(e), type: 'error'})
        });
      },
      removeLeaderLine : function () {
        if(this.lineArr){
          this.lineArr.forEach(item => {item.remove();});
          this.lineArr=[];
        }

      },
      handleEdit: function (index, row) {
        this.removeLeaderLine();
        this.editTestCaseForm = Object.assign({},row);
        this.$router.push({name:'edit',params:{name:'edit',data:this.editTestCaseForm}});
      },
      handleCopy: function (index,row){
        this.removeLeaderLine();
        this.editTestCaseForm = Object.assign({},row);
        this.$router.push({name:'add',params:{name:'copy',data:this.editTestCaseForm}});
      },
      handleAdd : function (){
        this.$router.push({name:'add',params:{name:'add'}});
      },

      changeRunTestCaseBtnStatus: function (sels) {
        if (sels.length == 1 && sels[0].isReady) {
          this.runTestCaseBtnDisabled = false;
        } else {
          this.runTestCaseBtnDisabled = true;
        }
      },
      selsChange: function (sels) {
        this.sels = sels;
        if(sels.length === 1){
          if(JSON.stringify(sels[0].relationship)=== JSON.stringify({})){
            this.prepareDataBtn = true;
          } else {
            this.prepareDataBtn = false;
            this.currentSelection = sels[0];
          }
        } else {
          this.prepareDataBtn = true;
        }
        this.changeRunTestCaseBtnStatus(sels);

      },
      batchRemove :function(){
        let testCaseIds = this.sels.map(item => item.testCaseId).toString();
        this.$confirm('are you sure？', 'Tip', {
          type: 'warning'
        }).then(() => {
          let url = 'testcase/batchremove/'+testCaseIds;
          this.listLoading = true;
          this.$http.delete(url).then(res=>{
            if(res.status === '200') {
              this.listLoading = false;
              this.$message({
                message: 'delete success',
                type: 'success'
              });
              this.getTestCase();
            } else {
              this.$message({
                message: 'error'+ res.reason,
                type: 'error'
              });
            }
          })
        }).catch((e) => {
          this.$message({
            type: 'error',
            message: e,
          })
        })
      },
      runTestCase:function () {
        let url = 'runOneTestCase/' + this.sels[0].testCaseId;
        console.log(url);
        this.$http.get(url).then((res)=>  {
          if(res.bodyText==="ok"){
            this.$message({
              type:'success',
              message:'Run test case success.Please wait.'
            })
          }else{
            this.$message({
              type:'error',
              message:res.bodyText
            })
          }
        },(response) => {
          this.$message({
            type:'error',
            message:response
          })
        });
      },
    changeBorderColor: function(elementId, color) {
      document.getElementById(elementId).style['border'] = "4px solid " + color;
      this.adjustLeaderLinePosition();
    },
    getOrderedDependencies: function(testCaseId, callback) {
      let getOrderedDependenciesURL = '/testcase/getDependencyTestcase/' + testCaseId;
      this.$http.get(getOrderedDependenciesURL).then(res => {
        if (res.data) {
          this.orderedDependenciesList = res.data;
          callback(this.currentSelection.relationship._id + '_' + this.orderedDependenciesList[0].testCaseId, '#FF9900');
        }
      })
    },
    prepareTestCaseData: function () {
      let url = 'prepare/'+ this.sels[0].testCaseId;
        this.$http.get(url).then(res => {
          if(res.bodyText==="ok"){
            this.$message({
              type:'success',
              message:'trigger success please wait'
            })
            this.getOrderedDependencies(this.sels[0].testCaseId, this.changeBorderColor);
          } else {
            this.$message({
              type:'error',
              message:res.bodyText
            })
          }
        })
    },
      adjustLeaderLinePosition : function () {
        this.lineArr.forEach(item=>{
          item.position();
        });
      },
//      updateTestCase: function (testCaseParams) {
//        let url = 'testcase/edit';
//        this.$http.put(url, {params: testCaseParams}).then((res) => {
//          if (res.body.status === '400') {
//            this.$message({
//              type: 'error',
//              message: res.body.reason
//            })
//          } else {
//            console.log('update isReady to true success');
//          }
//        });
//      },
      updateIsReady: function (relationshipId) {
        let completedFlag = true;
        this.currentSelection.relationship.dependency.forEach(item => {
          if (document.getElementById(relationshipId + '_' + item.testCaseId).style['border'] !== "4px solid rgb(0, 255, 52)") {
            completedFlag = false;
          }
        });
        if (completedFlag) {
          this.currentSelection.isReady = true;
//          this.updateTestCase({isReady: true, testCaseId: this.currentSelection.testCaseId});
        }
      },
      changeNextBorderColor: function (testCaseId, relationshipId) {
        var self = this;
        self.orderedDependenciesList.forEach(function (dependency, index) {
          if (dependency.testCaseId == testCaseId && index + 1 < self.orderedDependenciesList.length) {
            self.changeBorderColor(relationshipId + '_' + self.orderedDependenciesList[index + 1].testCaseId, '#FF9900');
            return;
          }
        })
      }
    },
    sockets:{
      connect: function(){
        console.log("connected with socket server");
//        this.$socket.emit('UI','request connect');
      },
      onVerifierResult: function (data) {
        console.log('verifier data come ', data);
        if (!data) {
          return;
        }
        let relationshipId = this.currentSelection.relationship._id;
        if (data.status === "success" && data.testCaseId) {
          this.changeBorderColor(relationshipId + '_' + data.testCaseId , 'rgb(0, 255, 52)')
          this.changeNextBorderColor(data.testCaseId, relationshipId)
        } else {
          this.changeBorderColor(relationshipId + '_' + data.testCaseId , 'red');
          return;
        }
        this.updateIsReady(relationshipId);
      }
    },
    mounted() {

    },
    created() {
      this.getLightWeightTestCaseList();
      this.getTestCase();
      this.$socket.emit('UI','request connect');

    },
    destroyed() {
      this.removeLeaderLine();
    }
  }
</script>
<style >body {
  font-family: Menlo, Consolas, monospace;
  color: #444;
}

ul {
  padding-left: 3em;
  line-height: 5em;
  margin-top: 15px;
  list-style-type: dot;
}
.root {
  border-radius: 25px;
  width:50px;
  border:5px solid transparent;
  margin-left:40em;
  /*margin-bottom:2em;*/
  height:50px;
  background-color: red;
}

.secondCircle {
  width:40px;
  border:6px solid white;
  height:40px;
  margin:0 auto;
  border-radius: 20px;
  background-color: red;
}



  .msg-expand {
    font-size: 0;
  }
  .msg-expand label {
    color: #3173ff;
  }
  .msg-expand .el-form-item {
    width: 95%;
  }
</style>
